/*******************************************************************************
 * Copyright (c) 2012 Germain Aubert.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 ******************************************************************************/ 
package com.mgs.fwk.controller
{
	import com.mgs.fwk.context.ApplicationContext;
	import com.mgs.fwk.handlers.ActionHandler;
	import com.mgs.product.tagger.actions.ApplicationAction;
	
	import flash.net.getClassByAlias;
	import flash.utils.Dictionary;
	
	import mx.core.ClassFactory;
	import mx.utils.ObjectUtil;

	public class ActionDispatcher
	{
		private var mapActionToId:Vector.<Class> = new Vector.<Class>();
		private var mapIdToHandlers:Vector.<Vector.<Class>> = new Vector.<Vector.<Class>>();
		
		
		public function ActionDispatcher()
		{
		}
		
		protected function register(action:Class, handler:Class):void
		{
			var index:int = mapActionToId.indexOf(action);
			if(index < 0){
				mapActionToId.push(action);
				index = mapActionToId.length - 1;
				mapIdToHandlers.push(new Vector.<Class>());
			}
			if(mapIdToHandlers[index].indexOf(handler) < 0){
				mapIdToHandlers[index].push(handler);
			}
		}
		
		public function processAction(context:ApplicationContext, action:ApplicationAction):void
		{
			var found:Boolean = false;
			for (var i:int = 0 ; i<mapActionToId.length ; i++)
			{
				var actionClass:Class = mapActionToId[i];
				if(action is actionClass)
				{
					for each(var handler:Class in mapIdToHandlers[i])
					{
						(new handler() as ActionHandler).execute(context, action);
					}
					found = true;
					break;
				}
			}
			if(!found){
				trace("unhandled action " + action);
			}
		}
	}
}